import React from 'react';
import cn from 'classnames';
import s from './style.module.css';
import ms from 'ms';
import { Input, Select } from '@knownsec/react-component';
// import SelectAnt from '../SelectAnt/index';

export default function CollectFrequency({ className, value, onChange, maxFreq,disabled }) {
  let unit = 'm';
  let num;
  if (value) {
    const nv = value * 1000;
    const freq = ms(nv);
    unit = value ? freq.replace(/\d*/, '') : 'd';
    num = parseInt(freq.replace(/[a-zA-Z]/, ''), 10);
    if (nv % ms('30d') === 0) {
      unit = 'month';
      num = nv / ms('30d');
    } else if (nv % ms('1w') === 0) {
      unit = 'w';
      num = nv / ms('1w');
    }
  }
  // console.log('时间：' + num + unit);
  const [val, setVal] = React.useState(unit);
  const [valInp, setValInp] = React.useState(num);
  React.useEffect(() => {
    setValInp(num);
    setVal(unit);
  }, [value]);

  const handleChange = (units, nums) => {
    let unit_ = units ? units : 'm';
    let num_ = nums ? JSON.parse(nums) : 0;
    let time = ms(`${num_}${unit_}`) / 1000;
    if (units === 'month') {
      time = ms(`${num_ * 30}d`) / 1000;
    }
    const freq = ms(time*1000);
    console.log('选择的时间单位time'+ms(freq)/1000);
    onChange(ms(freq)/1000);
  };
  const option = [
    { value: 'm', label: '分钟' },
    { value: 'h', label: '小时' },
    { value: 'd', label: '天' },
    { value: 'w', label: '周' },
    { value: 'month', label: '月' },
  ];
  return (
    <div className={cn(className, s.collectFrequency)}>
      <Input
        pro
        className={s.inp}
        value={valInp}
        disabled={disabled}
        onChange={(e) => {
          let num = e.value;
          if (isNaN(num)) {
            return;
          }
          num > 60 && (num = 60);
          num < 0 && (num = 1);
          setValInp(num);
          handleChange(val, num);
        }}
      />
      <Select
        pro
        option={option}
        className={s.sel}
        value={[val]}
        disabled={disabled}
        onChange={({ selectedItem }) => {
          setVal(selectedItem[0].value);
          handleChange(selectedItem[0].value, num);
        }}
      />
    </div>
  );
}
